package model;

import essenceClasses.User;
import interfaceModel.IUserModel;


import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Алексей
 * Date: 31.05.14
 * Time: 20:25
 * To change this template use File | Settings | File Templates.
 */
public class UserModel implements IUserModel {

    Connection conn = null;

    public UserModel() {
        conn = Connector.getConnection();
    }


    @Override
    public List<User> getAllUser() throws SQLException {

        List<User> list = new LinkedList<User>();
        Statement statement = conn.createStatement();
        ResultSet result = statement.executeQuery("SELECT * FROM userdb");
        while (result.next()) {
            list.add(new User(result.getInt("id"), result.getString("login"),
                    result.getString("password"), result.getString("FIO"), result.getInt("access")));
        }
        return list;
    }

    @Override
    public User getUser(String login) throws SQLException {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM userdb WHERE login = ?");
        preparedStatement.setString(1, login);
        ResultSet resultSet = preparedStatement.executeQuery();
        User user = null;
        while (resultSet.next()) {
            user = new User(resultSet.getInt("id"), resultSet.getString("login"),
                    resultSet.getString("password"), resultSet.getString("FIO"), resultSet.getInt("access"));
        }
        return user;
    }

    public User addUser(String login, String password, String fio, int access) throws SQLException {
        PreparedStatement preparedStatement = null;
        String insertuserSQL = "INSERT INTO userdb"
                + "(login, password, FIO, access) VALUES"
                + "(?,?,?,?)";
        preparedStatement = conn.prepareStatement(insertuserSQL);
        preparedStatement.setString(1, login);
        preparedStatement.setString(2, password);
        preparedStatement.setString(3, fio);
        preparedStatement.setInt(4, access);
        preparedStatement.executeUpdate();
        return getUser(login); // найдем в базе нашего юзера добавленного, так как id присваивает mySql.
    }

    @Override
    public int getAccesUser(String login) throws SQLException {
        PreparedStatement preparedStatement = null;
        preparedStatement = conn.prepareStatement("SELECT access FROM userdb WHERE login = ?");
        preparedStatement.setString(1, login);
        ResultSet result = preparedStatement.executeQuery();
        int access = 0;
        if (result.next()) {
            access = result.getInt("access");
        }
        return access;
    }


}
